package com.fsi.server;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

public class PhotoServlet extends HttpServlet implements Servlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		try {
			ServletFileUpload upload = new ServletFileUpload();
			upload.setSizeMax(50000);
			res.setContentType("text/html");

			try {
				FileItemIterator iterator = upload.getItemIterator(req);
				while (iterator.hasNext()) {
					FileItemStream item = iterator.next();
					InputStream in = item.openStream();

					if (item.isFormField()) {
					} else {
						String fieldName = item.getFieldName();
						String fileName = item.getName();
						String contentType = item.getContentType();
						String customerID = req.getParameter("customerid");
						boolean isMainImage = req.getParameter("ismainimage") == "true";
						String title = req.getParameter("title");

						byte[] contentBytes = null;
						try {
							contentBytes = IOUtils.toByteArray(in);
							PhotoDAO.get()
									.updatePhoto(fileName, contentBytes,
											contentType, customerID,
											isMainImage, title);

						} finally {
							IOUtils.closeQuietly(in);
						}

					}
				}
			} catch (SizeLimitExceededException e) {
				throw new Exception(e);
			}
		} catch (Exception ex) {

			throw new ServletException(ex);
		}
	}

}
